package swa.group22;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

import swa2012.telco.broker.Broker;
import swa2012.telco.broker.beans.BrokerRegistrationStatus;
import swa2012.telco.broker.beans.Provider;

/**
 * Main class for the Provider of Assignment 3.
 * Handles the initialization for the client and message containers as well as the proxy initialization for the BrokerService interaction.
 * 
 * @author group 22
 *
 */

public class ProviderApplication {

	// our group number is our provider ID
	private String providerID = "22";
	
	// defining Webservices

	private Broker broker;
	
	// Webservice for our Client
	private ProviderService providerService;
	
	// Webservice for the broker
	private ProviderBrokerCallback providerBrokerCallback;
	
	// initializing containers
	private ClientStore clientStore = new ClientStore();
	private MessageStore messageStore = new MessageStore();
	private JaxWsProxyFactoryBean factory;
	
	// Beans
	private Provider provider = null;
	
	
	public ProviderApplication() {
			

		factory = new JaxWsProxyFactoryBean();
		factory.setServiceClass(Broker.class);
		factory.setAddress("https://swa.univie.ac.at/TelcoBroker/BrokerService");
		
		broker = (Broker) factory.create();

		
		// Webservices
		providerService = new ProviderService(clientStore, messageStore, this);
		providerBrokerCallback = new ProviderBrokerCallback(clientStore, messageStore);
	}
	
	/**
	 * Registers itself at the Broker with the callback address for WebService interaction
	 * 
	 * @param url
	 * @return BrokerRegistrationStatus Enum
	 * @throws URISyntaxException
	 */
	public BrokerRegistrationStatus registerAtBroker(String url) throws URISyntaxException {
		URI brokerAddress = new URI(url);
		provider = new Provider(providerID, brokerAddress);
		broker.deregisterProvider(provider);
		return broker.registerProvider(provider);

	}
	/**
	 * De-registers itself at the Broker
	 * 
	 * @return BrokerRegistrationStatus Enum
	 */
	
	public BrokerRegistrationStatus deregisterAtBroker() {
		return broker.deregisterProvider(provider);
	}
	
	/**
	 * 
	 * @return the Broker proxy object for interaction with its webservice
	 */
	public Broker getBroker() {
		return broker;
	}
	
	/**
	 * 
	 * @return the callback object for the BrokerCallback
	 */
	public ProviderBrokerCallback getProviderBrokerCallback() {
		return providerBrokerCallback;
	}
	
	/**
	 * 
	 * @return the provider bean
	 */
	public Provider getProvider() {
		
		return provider;
	}
	
	/**
	 * 
	 * @return the object for the client webservice
	 */
	public ProviderService getProviderService() {
		return providerService;
	}
	

	/**
	 * assures the de-registering at the broker before deleting the object
	 */
	public void finalize() throws Throwable {
		this.deregisterAtBroker();
	}
	

	
}
